package com.wlr.study.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁的原理
 *
 * @author lrwang
 * @version 1.0
 * @date 2021/9/14 22:55
 */
public class WriteAndReadSync {
    static AtomicInteger a = new AtomicInteger(0);
    static volatile Map<String, Object> map = new HashMap<>();
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public void write(String key, Object value) {
        lock.writeLock().lock();
        try {
            TimeUnit.MILLISECONDS.sleep(300);
            System.out.println("写入中 \t come in this Thread \t" + WriteAndReadSync.a.incrementAndGet());
            map.put(key, value);
            System.out.println("写入完毕\t complete write value: \t" + WriteAndReadSync.a);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.writeLock().unlock();
        }
    }

    public void read(String key) {
        lock.readLock().lock();
        try {
            TimeUnit.MILLISECONDS.sleep(300);
            System.out.println("读取中" + Thread.currentThread().getName() + "\t value is \t" + WriteAndReadSync.a);
            map.get(key);
            System.out.println("读取完毕" + Thread.currentThread().getName() + "\t value is \t" + WriteAndReadSync.a);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.readLock().unlock();
        }
    }

    public static void main(String[] args) {
        WriteAndReadSync writeAndReadSync = new WriteAndReadSync();
        for (int i = 0; i < 20; i++) {
            int temp = i;
            new Thread(() -> {
                writeAndReadSync.write(String.valueOf(temp), temp);
                writeAndReadSync.read(String.valueOf(temp));
            }, String.valueOf(i)).start();
        }
//        for (int i = 0; i < 20; i++) {
//            int temp = i;
//            new Thread(() -> {
//                user.read(String.valueOf(temp));
//            }, String.valueOf(i)).start();
//        }
    }
}
